<?php
@header('Content-Type: text/html; charset=UTF-8');
@ignore_user_abort(true);
@set_time_limit(0);

$mysql = require_once __DIR__ . '/../application/index/database.php';
try {
    $pdo = new PDO("mysql:host={$mysql['hostname']};dbname={$mysql['database']};port={$mysql['hostport']}", $mysql['username'], $mysql['password']);
} catch (Exception $e) {
    exit('链接数据库失败:' . $e->getMessage());
}
$pdo->exec("set names utf8");

$keyRow = $pdo->query("select value from dg_configs where vkey='cronkey' limit 1")->fetchColumn();
$key = isset($_GET['key']) ? $_GET['key'] : null;
if (!($keyRow && $key && $key == $keyRow)) {
    exit('监控识别码不正确！');
}

$stmt = $pdo->query("SELECT
	b.qid,
	b.uin,
	b.skey,
	GROUP_CONCAT(a.id) AS ids,
	GROUP_CONCAT(a.tid) AS tids
FROM
	dg_orders AS a
LEFT JOIN dg_qqs AS b ON b.qid = a.qid
WHERE
	a.tid IN (2, 3, 4, 5, 6, 7, 8)
AND b.cookiezt = 0
AND a.zt = 0
AND (
	a.isfinish = 0
	OR TO_DAYS(a.lastcheck) != TO_DAYS(NOW())
)
AND a.endtime > now()
AND a.zt != 90
GROUP BY
	uin
ORDER BY b.lastcheck asc limit 5
");

$num = 0;
while ($row = $stmt->fetch()) {
	$num++;
    $pdo->exec("update dg_qqs set lastcheck=NOW() where qid='{$row['qid']}' limit 1");
    $uin = $row['uin'];
    $skey = $row['skey'];
    $g_tk = get_g_tk($skey);
    $levelInfoUrl = "http://cgi.vip.qq.com/profile/QQLevelInfo?g_tk={$g_tk}&p_tk=&callback=";
    $json = get_curl($levelInfoUrl, null, $levelInfoUrl, "uin=o0{$uin}; skey={$skey}");
    $arr = json_decode($json, true);
    if (isset($arr['ret']) && $arr['ret'] == 0) {
        echo "{$uin}:";
        $ids = explode(',', $row['ids']);
        $tids = explode(',', $row['tids']);
        foreach ($tids as $k => $tid) {
            echo checkFinish($arr, $tid, $ids[$k]) . "，";
        }
        echo "<br>";
    } elseif (isset($arr['is_login']) && $arr['is_login'] == 0) {
        $pdo->exec("update dg_qqs set cookiezt=1 where qid='{$row['qid']}' limit 1");
        echo "{$uin}:COOKIE过期<br>";
    } else {
        echo "{$uin}:ERROR! {$json} <br>";
    }
}

echo "<br>总共执行{$num}个QQ。";

function checkFinish($arr, $tid, $id = 0)
{
    global $pdo;
    $isFinish = false;
    switch ($tid) {
        case 7:
            //QQ勋章墙
            if ($arr['iMedal']) {
                $ret = "勋章：完成";
                $isFinish = true;
            } else {
                $ret = "勋章：补挂";
            }
            break;
        case 6:
            //手机游戏
            if ($arr['iMobileGameOnline']) {
                $ret = "手游：完成";
                $isFinish = true;
            } else {
                $ret = "手游：补挂";
            }
            break;
        case 3:
            //手机QQ在线
            if ($arr['iMobileQQOnline']) {
                $ret = "手机：完成";
                $isFinish = true;
            } else {
                $ret = "手机：补挂";
            }
            break;
        case 2:
            //电脑QQ在线
            if ($arr['iPCQQOnline']) {
                $ret = "电脑：完成";
                $isFinish = true;
            } else {
                $ret = "电脑：补挂";
            }
            break;
        case 4:
            //QQ安全管家
            if ($arr['iPCSafeOnline']) {
                $ret = "管家：完成";
                $isFinish = true;
            } else {
                $ret = "管家：补挂";
            }
            break;
        case 8:
            //钱包签到
            if ($arr['iQWalletSign']) {
                $ret = "钱包：完成";
                $isFinish = true;
            } else {
                $ret = "钱包：补挂";
            }
            break;
        case 5:
            //手机版QQ音乐
            if ($arr['iUseQQMusic']) {
                $ret = "音乐：完成";
                $isFinish = true;
            } else {
                $ret = "音乐：补挂";
            }
            break;
        case 99:
            //非隐身在线
            if ($arr['iNoHideOnline']) {
                $ret = "非隐身在线：完成";
                $isFinish = true;
            } else {
                $ret = "非隐身在线：补挂";
            }
            break;
        default:
            $ret = "未知";
    }

    if ($isFinish) {
        $pdo->exec("update dg_orders set zt=0,isfinish=1,lastcheck=NOW() where id='{$id}' limit 1");
    } else {
        $pdo->exec("update dg_orders set zt=1,isfinish=0,lastcheck=NOW() where id='{$id}' limit 1");
    }
    return $ret;
}


function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $klsf[] = "Accept:*/*";
    $klsf[] = "Accept-Encoding:gzip,deflate,sdch";
    $klsf[] = "Accept-Language:zh-CN,zh;q=0.8";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $klsf);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, "http://m.qzone.com/infocenter?g_f=");
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0');
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);//主要头部
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//跟随重定向
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}

function get_g_tk($skey)
{
    $salt = 5381;
    $md5key = 'tencentQQVIP123443safde&!%^%1282';
    $hash = array();
    $hash[] = ($salt << 5);
    $len = strlen($skey);
    for ($i = 0; $i < $len; $i++) {
        $ASCIICode = mb_convert_encoding($skey[$i], 'UTF-32BE', 'UTF-8');
        $ASCIICode = hexdec(bin2hex($ASCIICode));
        $hash[] = (($salt << 5) + $ASCIICode);
        $salt = $ASCIICode;
    }
    $md5str = md5(implode($hash) . $md5key);
    return $md5str;
}